package com.yfqy.admin.service.impl;

import com.aliyun.oss.OSS;
import com.yfqy.admin.conf.oss.AliyunOSSConfig;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class AliyunOSSService {

    private final OSS ossClient;
    private final AliyunOSSConfig aliyunOSSConfig;

    public AliyunOSSService(OSS ossClient, AliyunOSSConfig aliyunOSSConfig) {
        this.ossClient = ossClient;
        this.aliyunOSSConfig = aliyunOSSConfig;
    }

    /**
     * 上传文件
     *
     * @param file   文件
     * @param folder 上传到的文件夹
     * @return 文件访问URL
     */
    public String upload(MultipartFile file, String folder) {
        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = folder + "/" + UUID.randomUUID() + fileExtension;

            // 上传文件
            ossClient.putObject(
                    aliyunOSSConfig.getBucketName(),
                    fileName,
                    file.getInputStream()
            );

            // 返回文件访问URL
            return aliyunOSSConfig.getUrlPrefix() + fileName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /**
     * 批量上传文件
     *
     * @param files  文件列表
     * @param folder 上传到的文件夹
     * @return 文件访问URL列表
     */
    public List<String> uploadBatch(MultipartFile[] files, String folder) {
        return Arrays.stream(files)
                .map(file -> upload(file, folder))
                .collect(Collectors.toList());
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件URL
     */
    public void delete(String fileUrl) {
        String fileName = fileUrl.replace(aliyunOSSConfig.getUrlPrefix(), "");
        ossClient.deleteObject(aliyunOSSConfig.getBucketName(), fileName);
    }
}